import sensor from '@blueos.hardware.sensor.sensor'
import health from '@blueos.health.health'
import prompt from '@blueos.window.prompt'


// 监听心率
export const listenHeartRate = ()=>{
  return new Promise((resolve, reject) => {
    health.getRecentSamples({
      dataTypes:[health.DATA_TYPES.HEART_RATE],
      success:function(res){
        // console.log(`最近一次心率${Number(res.dataType)}测试:${heartRate}`)
        resolve(res[0].data.value)
      },
      fail:function(data, code){
          console.log("获取心率失败, data=${data}, code=${code}")
          resolve(0)
          // Math.floor(Math.random() * (140 - 60 + 1)) + 60;
      }
    })
  })
};

// 监听加速度
export const listenAccelerometer = () => {
  return new Promise((resolve, reject) => {
    let accelerometer = 10;
    let count = 0; 
    const maxIterations = 20;
    prompt.showToast({
      message:`请快速挥拳，帮助小球获取加速度`,
    })
    const intervalId = setInterval(() => {
      sensor.subscribeAccelerometer({
        callback: function (ret) {
          console.log(`加速度 x = ${ret.x}, y = ${ret.y}, z = ${ret.z}`);
          let x = Math.abs(Number(ret.x))
          let y = Math.abs(Number(ret.y))
          let z = Math.abs(Number(ret.z))
          if (accelerometer< Math.sqrt(x*x+y*y+z*z)){
            accelerometer = Math.sqrt(x*x+y*y+z*z)
          }
        },
        fail: function (data, code) {
          console.log(`handling fail, data = ${data}`);
          console.log(`handling fail, code = ${code}`);
          if (accelerometer < 0) {
            accelerometer = 0;
          }
        },
      });

      count++;
      if (count >= maxIterations) {
        clearInterval(intervalId);
        accelerometer = Math.round(accelerometer)
        prompt.showToast({
          message:`球速设置成功：${accelerometer}`,
        })
        resolve(accelerometer);
      }
    }, 100); // 每隔 200ms 执行一次
  });
};

// 监听罗盘数据
export const listenCompass = ()=>{
  return new Promise((resolve, reject) => {
    sensor.subscribeCompass({
      callback: function (ret) {
        resolve(ret.direction%180)
      },
      fail: function (data, code) {
        resolve(60)
      },
    })
  })

}

// 监听陀螺仪
export const listenGyroscope = ()=>{
  return new Promise((resolve, reject) => {
    sensor.subscribeGyroscope({
      callback: function (ret) {
        resolve(`陀螺仪数据 x = ${ret.x}, y = ${ret.y}, z = ${ret.z}`)
      },
      fail: function (data, code) {
        resolve(`data=${data},code=${code}`)
      },
    })
  })
}